<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantCode"
            clearable
            placeholder="请选择工厂"
          >
            <el-option
              v-for="item in plants"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.organizationCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型编号">
          <el-input
            v-model="searchParam.workCalendarTypeCode"
            placeholder="请输入类型编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableBatchDisabled()"
          ><i-ep-delete />批量停用</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        :maxHeight="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column
          label="工厂"
          prop="plantCode"
          width="100"
          show-overflow-tooltip
          header-align="center"
        />
        <el-table-column
          label="工作日历类型编号"
          prop="workCalendarTypeCode"
          min-width="120"
          show-overflow-tooltip
          header-align="center"
        />
        <el-table-column
          label="工作日历类型名称"
          prop="workCalendarTypeName"
          min-width="120"
          show-overflow-tooltip
          header-align="center"
        />

        <el-table-column label="工作日" min-width="500" header-align="center">
          <template #default="scope">
            <div
              style="display: flex; justify-content: center"
              key="componentKey"
            >
              <el-checkbox-button
                :value="1"
                key="1"
                :checked="scope.row.workingDayMon === 1"
                onclick="return false;"
              >
                周一
              </el-checkbox-button>
              <el-checkbox-button
                :value="1"
                key="2"
                :checked="scope.row.workingDayTue === 1"
                onclick="return false;"
              >
                周二
              </el-checkbox-button>
              <el-checkbox-button
                :value="1"
                key="3"
                :checked="scope.row.workingDayWed === 1"
                onclick="return false;"
              >
                周三
              </el-checkbox-button>
              <el-checkbox-button
                :value="1"
                key="4"
                :checked="scope.row.workingDayTur === 1"
                onclick="return false;"
              >
                周四
              </el-checkbox-button>
              <el-checkbox-button
                :value="1"
                key="5"
                :checked="scope.row.workingDayFri === 1"
                onclick="return false;"
              >
                周五
              </el-checkbox-button>
              <el-checkbox-button
                :value="1"
                key="6"
                :checked="scope.row.workingDaySat === 1"
                onclick="return false;"
              >
                周六
              </el-checkbox-button>
              <el-checkbox-button
                :value="1"
                key="7"
                :checked="scope.row.workingDaySon === 1"
                onclick="return false;"
              >
                周日
              </el-checkbox-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="启用状态"
          prop="enabled"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />

        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />
        <el-table-column
          label="修改时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />

        <el-table-column
          label="修改人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="120"
          align="center"
        >
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
                ><i-ep-search />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialog(scope.row)"
                ><i-ep-edit
              /></el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="删除"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="handleTableDelete(scope.row.id)"
                ><i-ep-delete
              /></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mdmworkcalendartype-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id: string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary,useComputeTableHeight } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MDMMDMWORKCALENDARTYPE",
  inheritAttrs: false,
});

let plants = ref([]);
let days = ref([]);
const componentKey = ref(0);
// 请求参数
const requestApi = "/mdm/mdmworkcalendartype/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {};

const deleteParam = {
  api: "/mdm/mdmworkcalendartype/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

// watch(
//   () => tableData.value,
//   (newVal) => {
//     console.log("gengxinla");
//   },
//   {
//     // deep: true,
//   }
// );
// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlants();
  getFreeDay();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mdm/mdmworkcalendartype/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
// function update() {
//   console.log("1111111111");
// }
watch(
  () => tableData.value,
  (newVal) => {
    console.log("gengxinla");
    componentKey.value++;
    console.log(componentKey.value);
    //$forceUpdate();
  }
);

async function getPlants() {
  const data = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
  searchParam.value.plantCode = plants.value[0].organizationCode;
}
async function getFreeDay() {
  const data = await request({
    url: "/mdm/mdmworkcalendar/getWithDetails",
    method: "post",
    data: { workCalendarYear: 2024, plantId: "1000" },
  });
  days.value = data.data;
}
async function handleTableBatchDisabled() {
  // 弹出确认提示框
  ElMessageBox.confirm("确定停用所选项吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      console.log(ids.value);
      try {
        loading.value = true; // 显示加载状态
        await request({
          url: "/mdm/mdmworkcalendartype/batchDisabled",
          method: "post",
          data: { ids: ids.value },
        });
        reset();
      } catch (error) {
        console.error("请求发生错误:", error);
      } finally {
        loading.value = false; // 隐藏加载状态
      }
    })
    .catch(() => {
      // 用户取消操作
      console.log("用户取消操作");
    });
}
/** 打开工作日历类型表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改工作日历类型";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增工作日历类型";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
function handleClick() {
  // 空方法或者不做任何操作
}
/** 打开工作日历类型表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "工作日历类型详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
</script>
